package com.harmontronics.app.pedestal;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.harmontronics.app.pedestal.agent.WebActivity;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class SplashActivity extends AppCompatActivity {

    private static final String[] sPermissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    private Disposable mCopyTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        // get permissions
        PermissionUtils.permission(sPermissions).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(@NonNull @NotNull List<String> granted) {
                permissionOnGranted();
            }

            @Override
            public void onDenied(@NonNull @NotNull List<String> deniedForever, @NonNull @NotNull List<String> denied) {
                ToastUtils.showLong("请允许所有权限后使用");
            }
        }).request();
    }

    private void permissionOnGranted() {
        // copy start resources to files dir
        mCopyTask = Observable.create(new ObservableOnSubscribe<Object>() {
                    @Override
                    public void subscribe(@NotNull ObservableEmitter<Object> emitter) throws Exception {
                        ResourceUtils.copyFileFromAssets("static", AppConstants.DOWNLOAD_START_FOLDER);
                        emitter.onNext("");
                        emitter.onComplete();
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (checkGpsIsOpen()) {
                            goMain();
                        } else {
                            new AlertDialog.Builder(SplashActivity.this).setTitle("提示")
                                    .setMessage("系统检测到您当前未开启定位功能，可能导致部分功能无法正常使用，是否立即开启？")
                                    //  取消选项
                                    .setNegativeButton("稍后", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            // 关闭dialog
                                            dialogInterface.dismiss();
                                            goMain();
                                        }
                                    })
                                    //  确认选项
                                    .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            //跳转到手机原生设置页面
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            SplashActivity.this.startActivityForResult(intent, GPS_REQUEST_CODE);
                                        }
                                    })
                                    .setCancelable(false)
                                    .show();

                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mCopyTask && !mCopyTask.isDisposed()) {
            mCopyTask.dispose();
            mCopyTask = null;
        }
    }

    private int GPS_REQUEST_CODE = 100;

    private boolean checkGpsIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE) {
            goMain();
        }
    }

    private void goMain() {
        Intent intent = new Intent(SplashActivity.this, WebActivity.class);
        startActivity(intent);
        finish();
    }
}